// pages/payment/index.js
const app = getApp() // 引入app
import _request from '../../../utils/request.js'
import {
  getTime,
  getTouchData,
  toDecimal2,
} from '../../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [{
        title: '微信支付',
        img: 'wxpay.png',
      },
      {
        title: '余额支付',
        img: 'yepay.png'
      }
    ],
    listindex: -1,
    imgUrl: app.globalData.imgUrl, //全局img路径
    wallet: 0,
    mealObj: null,
    password: '',
    showpay: false,
    bool: false,
    isFocus: false,
    value: '',
  },


  // 点击事件
  onClick(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setData({
      listindex: index,
      bool: true,
      value: '',
    })
  },

  // 获取密码
  getpassword(e) {
    this.setData({
      password: e.detail.inputValue
    })
    if (this.data.password.length == 6) {
      _request.get('/settings/initPayWord', {
        userId: wx.getStorageSync('userid'),
      }).then((res) => {
        if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
          this.setData({
            showpay: false,
            value: '',
          })
          this.setData({
            password: '',
          })
          wx.showModal({
            title: '您还未设置密码',
            content: '请先设置密码',
            confirmText: '前往设置',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/setpaypassword/index',
                })
              } else if (res.cancel) {}
            }
          })
        } else if (res.data.message == '支付密码已设置' && res.data.data == 1) {
          _request.postObj('/settings/checkPayWord', {
            payWord: this.data.password,
            userId: wx.getStorageSync('userid'),
          }).then((res) => {
            if (res.data.code === 200) {
              this.walletPayment()
            }
          })
        }
      })

    }
  },

  // 取消支付
  onClickHide() {
    this.setData({
      showpay: false,
      value: '',
    })
  },

  // 支付
  onPayment() {
    if (!this.data.bool) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
        duration: 1000
      })
    } else if (this.data.bool && this.data.listindex == 1) {
      this.setData({
        showpay: true,
        isFocus: true
      })
    } else if (this.data.bool && this.data.listindex == 0) {
      wx.login({
        success: res => {
          this.wxPayment(res.code)
        }
      });
    }

  },

  // wx支付
  wxPayment(code) {
    let vm = this
    _request.postObj('/packagePay/wxAppletpay', {
      serviceId: this.data.mealObj.serviceId,
      money: this.data.mealObj.price,
      packageId: this.data.mealObj.packageId,
      code,
      userId: wx.getStorageSync('userid')
    }, app.globalData.userType).then((res) => {
      if (res.data.code == 200) {
        let data = {
          timeStamp: res.data.data.timestamp,
          nonceStr: res.data.data.nonceStr,
          package: res.data.data.pkg,
          signType: 'MD5',
          paySign: res.data.data.sign,
        }
        wx.requestPayment({
          ...data,
          success(res) {
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 1000
            })
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/mypreferentialcard/index',
              })
            }, 1000)
          },
          fail(res) {}
        })
      }
    }).catch((error) => {})
  },

  // 钱包支付 支付类型，1订单支付，2，订单加价
  walletPayment() {
    _request.postObj('/packagePay/yiyuePackagePay', {
      serviceId: this.data.mealObj.serviceId,
      money: this.data.mealObj.price,
      packageId: this.data.mealObj.packageId,
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      if (res.data.code == 200) {
        wx.showToast({
          title: '支付成功',
          icon: 'none',
          duration: 1000
        })
        this.setData({
          showpay: false,
          password: '',
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/mypreferentialcard/index',
          })
        }, 1000)
      }
    }).catch((error) => {

    })

  },

  // 获取账号余额 
  getCashInfo() {
    _request.get('/wallet/getCashInfo', {
      id: wx.getStorageSync('userid'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      this.setData({
        wallet: res.data.data.balance - res.data.data.freezebalance
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let data = JSON.parse(decodeURIComponent(options.data))
    data.price = toDecimal2(data.price)
    this.setData({
      mealObj: data,
    })
    this.getCashInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    _request.get('/settings/initPayWord', {
      userId: wx.getStorageSync('userid'),
    }).then((res) => {
      if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
        wx.showModal({
          title: '您还未设置密码',
          content: '请先设置密码',
          confirmText: '前往设置',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/setpaypassword/index',
              })
            } else if (res.cancel) {}
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})